<template>
  <div class="mistakes-page">
    <div class="header">
      <h2>错题本</h2>
      <div class="filter-box">
        <el-select v-model="selectedStatus" placeholder="选择状态" clearable style="width: 120px">
          <el-option label="未掌握" value="未掌握" />
          <el-option label="已复习" value="已复习" />
          <el-option label="已掌握" value="已掌握" />
        </el-select>
        <el-input v-model="searchContent" placeholder="输入题目关键字" clearable style="width: 200px" />
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>筛选
        </el-button>
        <el-button @click="refreshList">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </div>
    </div>

    <div class="mistakes-list" v-loading="loading">
      <div v-for="(mistake, index) in mistakes" :key="index" class="mistake-block">
        <div class="mistake-header-row">
          <div class="question-info-inline">
            <div class="question-text">{{ mistake.content }}</div>
          </div>
          <div class="header-tags">
            <el-tag type="danger" size="small" class="mistake-count-tag">错误次数: {{ mistake.mistakeCount }}</el-tag>
            <el-tag :type="getStatusTagType(mistake.status)" size="small" class="status-tag">{{ mistake.status }}</el-tag>
          </div>
        </div>
        <div class="mistake-content">
          <div class="answer-info">
            <div class="your-answer">
              <h4>您的答案</h4>
              <div class="wrong-answer">
                <template v-if="mistake.studentAnswers_string.includes('&')">
                  <div v-for="(answer, idx) in mistake.studentAnswers_string.split('&')" :key="idx" class="answer-item">
                    <span class="answer-index">第{{ idx + 1 }}次：</span>
                    <span class="answer-content">{{ answer }}</span>
                  </div>
                </template>
                <template v-else>
                  {{ mistake.studentAnswers_string }}
                </template>
              </div>
            </div>
            <div class="correct-answer">
              <h4>正确答案</h4>
              <div class="right-answer">{{ mistake.correctAnswer }}</div>
            </div>
          </div>
          <div class="mistake-footer">
            <div class="time-info">
              <span class="first-time"><i class="el-icon-time"></i> 首次错误：{{ formatDate(mistake.mistakeTime) }}</span>
              <span class="last-time"><i class="el-icon-time"></i> 最近错误：{{ formatDate(mistake.lastMistakeTime) }}</span>
            </div>
            <div class="actions">
              <template v-if="mistake.status === '未掌握'">
                <el-button 
                  type="primary" 
                  size="small"
                  round
                  @click="markAsResolved(index)"
                >
                  标记为已掌握
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  round
                  @click="markAsReviewed(index)"
                >
                  标记为已复习
                </el-button>
              </template>
              <template v-else-if="mistake.status === '已复习'">
                <el-button 
                  type="primary" 
                  size="small"
                  round
                  @click="markAsResolved(index)"
                >
                  标记为已掌握
                </el-button>
              </template>
              <template v-else-if="mistake.status === '已掌握'">
                <el-button 
                  type="warning" 
                  size="small"
                  round
                  @click="markAsUnmastered(index)"
                >
                  标记为未掌握
                </el-button>
              </template>
            </div>
          </div>
        </div>
      </div>
      <div v-if="mistakes.length === 0" class="empty-state">
        <el-empty description="暂无错题记录" />
      </div>
    </div>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getMistakeCollection, updateMistakeStatus } from '@/api/exam'
import { useUser } from '@/stores/userInfo'

const userStore = useUser()

// 错题本状态数据
const loading = ref(false)
const activeNames = ref([])
const selectedStatus = ref('')
const searchContent = ref('')
const mistakes = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取错题本数据
const fetchMistakes = async () => {
  loading.value = true
  try {
    const schoolNumber = userStore.userInfo?.schoolNumber
    if (!schoolNumber) {
      ElMessage.error('未获取到用户信息')
      return
    }
    
    // 修改请求参数的格式
    const params = {
      studentID: schoolNumber,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      searchContent: searchContent.value || '',
      status: selectedStatus.value || ''
    }
    
    const res = await getMistakeCollection(params)
    
    if (res.code === 200) {
      const allMistakes = res.data.data.map(item => ({
        id: item.mistake_id,
        examName: '错题记录',
        subject: '考试',
        type: item.questionContent.includes('?') ? 'choice' : 'text',
        content: item.questionContent,
        studentAnswers_string: item.studentAnswers_string,
        correctAnswer: item.standardAnswer,
        difficulty: 'medium',
        mistakeTime: item.mistakeTime,
        lastMistakeTime: item.lastMistakeTime,
        status: item.status,
        mistakeCount: item.mistakeCount
      }))
      // 排序：未掌握和已复习按错误次数降序，已掌握排最后
      const notMastered = allMistakes.filter(m => m.status !== '已掌握')
        .sort((a, b) => b.mistakeCount - a.mistakeCount)
      const mastered = allMistakes.filter(m => m.status === '已掌握')
      mistakes.value = [...notMastered, ...mastered]
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取错题本失败')
    }
  } catch (error) {
    ElMessage.error('获取错题本失败')
    console.error('错题本接口错误:', error)
  } finally {
    loading.value = false
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMistakes()
}

// 处理每页数量改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchMistakes()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchMistakes()
}

// 重置筛选
const refreshList = () => {
  selectedStatus.value = ''
  searchContent.value = ''
  currentPage.value = 1
  fetchMistakes()
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  const types = {
    'easy': 'success',
    'medium': 'warning',
    'hard': 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  const labels = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return labels[difficulty] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return date
}

// 标记为已掌握
const markAsResolved = async (index) => {
  const mistake = mistakes.value[index]
  if (mistake.status === '已掌握') return
  try {
    await updateMistakeStatus(mistake.id, '已掌握')
    mistakes.value[index].status = '已掌握'
    ElMessage.success('已标记为已掌握')
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

// 标记为已复习
const markAsReviewed = async (index) => {
  const mistake = mistakes.value[index]
  if (mistake.status === '已复习') {
    ElMessage.info('该题已是"已复习"状态')
    return
  }
  try {
    await updateMistakeStatus(mistake.id, '已复习')
    mistakes.value[index].status = '已复习'
    ElMessage.success('已标记为已复习')
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

// 标记为未掌握
const markAsUnmastered = async (index) => {
  const mistake = mistakes.value[index]
  try {
    await updateMistakeStatus(mistake.id, '未掌握')
    mistakes.value[index].status = '未掌握'
    ElMessage.success('已标记为未掌握')
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  if (status === '未掌握') return 'danger'
  if (status === '已复习') return 'info'
  if (status === '已掌握') return 'success'
  return 'default'
}

// 页面加载时获取数据
onMounted(() => {
  fetchMistakes()
})
</script>

<style lang="scss" scoped>
.mistakes-page {
  padding: 20px;
  background-color: #f6f8fa;
  min-height: 100vh;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    position: sticky;
    top: 0;
    z-index: 20;
    background: rgba(246, 248, 250, 0.95);
    box-shadow: 0 2px 8px 0 rgba(0,0,0,0.04);
    border-bottom: 1px solid #e4e7ed;
    padding: 8px 0 6px 0;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
      font-weight: bold;
      letter-spacing: 1px;
    }

    .filter-box {
      display: flex;
      gap: 10px;
      align-items: center;
      margin-left: 24px;
    }
  }

  .mistakes-list {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .mistake-block {
      background: #fff;
      border-radius: 10px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08);
      padding: 28px 32px 20px 32px;
      transition: box-shadow 0.2s;
      border-left: 6px solid #f56c6c;
      position: relative;
      &:hover {
        box-shadow: 0 4px 24px 0 rgba(0,0,0,0.13);
      }

      .mistake-header-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 18px;
      }
      .question-info-inline {
        flex: 1;
        .question-text {
          color: #222;
          line-height: 1.7;
          font-size: 16px;
          padding: 12px 16px;
          background-color: #f4f8ff;
          border-radius: 6px;
          border: 1px solid #e3eaf3;
          word-break: break-all;
        }
      }
      .header-tags {
        display: flex;
        flex-direction: row;
        gap: 10px;
        align-items: center;
        margin-left: 20px;
        .mistake-count-tag {
          margin: 0;
        }
        .status-tag {
          margin: 0;
        }
      }

      .mistake-content {
        .answer-info {
          display: flex;
          gap: 32px;
          margin-bottom: 18px;
          .your-answer, .correct-answer {
            flex: 1;
          }
          h4 {
            margin: 0 0 8px;
            color: #67c23a;
            font-size: 15px;
            font-weight: bold;
          }
          .your-answer h4 {
            color: #f56c6c;
          }
          .wrong-answer {
            color: #f56c6c;
            padding: 12px 16px;
            background-color: #fff0f0;
            border-radius: 6px;
            border: 1px solid #fde2e2;
            .answer-item {
              margin-bottom: 6px;
              padding-bottom: 6px;
              border-bottom: 1px dashed #fde2e2;
              &:last-child {
                margin-bottom: 0;
                padding-bottom: 0;
                border-bottom: none;
              }
              .answer-index {
                color: #909399;
                margin-right: 8px;
              }
              .answer-content {
                color: #f56c6c;
              }
            }
          }
          .right-answer {
            color: #67c23a;
            padding: 12px 16px;
            background-color: #f0f9eb;
            border-radius: 6px;
            border: 1px solid #e1f3d8;
          }
        }
        .mistake-footer {
          margin-top: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 10px;
          border-top: 1px solid #ebeef5;
          .time-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
            .first-time, .last-time {
              color: #909399;
              font-size: 14px;
              display: flex;
              align-items: center;
              i {
                font-size: 15px;
                margin-right: 4px;
                color: #b1b1b1;
              }
            }
          }
          .actions {
            display: flex;
            gap: 10px;
            .el-button {
              font-weight: bold;
              letter-spacing: 1px;
            }
          }
        }
      }
    }
    .empty-state {
      padding: 40px 0;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>